import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    Card,
    Button,
    Descriptions,
    Tag,
    Space,
    message,
    Modal,
    Divider
} from 'antd';
import {
    EditOutlined,
    ArrowLeftOutlined,
    CheckCircleOutlined,
    PlayCircleOutlined,  // 添加这个导入
    PauseCircleOutlined  // 添加这个导入
} from '@ant-design/icons';
import { taskService } from '../../services/taskService';
import StepList from '../Steps/StepList';
import ReviewForm from '../Reviews/ReviewForm';
import dayjs from 'dayjs';
import { PRIORITY_MAPPING } from '../../constants/priorityConstants';

const TaskDetails = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const [task, setTask] = useState(null);
    const [loading, setLoading] = useState(true);

    const fetchTask = useCallback(async () => {
        try {
            const response = await taskService.getTask(id);
            setTask(response.data);
        } catch (error) {
            message.error('获取任务详情失败');
            //console.error('Error fetching task:', error);
        } finally {
            setLoading(false);
        }
    }, [id]);

    useEffect(() => {
        fetchTask();
    }, [fetchTask]);

    const handleDelete = () => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个任务吗？此操作不可撤销。',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    await taskService.deleteTask(id);
                    message.success('任务删除成功');
                    navigate('/tasks');
                } catch (error) {
                    message.error('删除任务失败');
                }
            }
        });
    };

    const handleStatusChange = async (newStatus) => {
        try {
            await taskService.updateTask(id, { status: newStatus });
            setTask({ ...task, status: newStatus });
            message.success('任务状态更新成功');
        } catch (error) {
            message.error('更新任务状态失败');
        }
    };

    const getStatusColor = (status) => {
        const colors = {
            'TODO': 'default',
            'IN_PROGRESS': 'processing',
            'COMPLETED': 'success',
            'CANCELLED': 'error'
        };
        return colors[status] || 'default';
    };

    const getStatusText = (status) => {
        const texts = {
            'TODO': '待开始',
            'IN_PROGRESS': '进行中',
            'COMPLETED': '已完成',
            'CANCELLED': '已取消'
        };
        return texts[status] || status;
    };

    if (loading) {
        return <Card loading={loading} />;
    }

    if (!task) {
        return <Card>任务不存在</Card>;
    }

    return (
        <div>
            <Card
                title={
                    <Space>
                        <Button
                            icon={<ArrowLeftOutlined />}
                            onClick={() => navigate('/tasks')}
                        >
                            返回
                        </Button>
                        <span>{task.title}</span>
                    </Space>
                }
                extra={
                    <Space>
                        {task.status === 'TODO' && (
                            <Button
                                type="primary"
                                icon={<PlayCircleOutlined />}
                                onClick={() => handleStatusChange('IN_PROGRESS')}
                            >
                                开始任务
                            </Button>
                        )}
                        {task.status === 'IN_PROGRESS' && (
                            <Button
                                icon={<PauseCircleOutlined />}
                                onClick={() => handleStatusChange('TODO')}
                            >
                                暂停任务
                            </Button>
                        )}
                        {task.status === 'IN_PROGRESS' && (
                            <Button
                                type="primary"
                                icon={<CheckCircleOutlined />}
                                onClick={() => handleStatusChange('COMPLETED')}
                            >
                                完成任务
                            </Button>
                        )}
                        <Button
                            icon={<EditOutlined />}
                            onClick={() => navigate(`/tasks/${id}/edit`)}
                        >
                            编辑
                        </Button>
                    </Space>
                }
            >
                <Descriptions column={2} bordered>
                    <Descriptions.Item label="任务标题">{task.title}</Descriptions.Item>
                    <Descriptions.Item label="状态">
                        <Tag color={getStatusColor(task.status)}>
                            {getStatusText(task.status)}
                        </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="优先级">
                        {task.priority !== undefined && (
                            <Tag color={PRIORITY_MAPPING[task.priority]?.color || 'default'}>
                                {PRIORITY_MAPPING[task.priority]?.text || '未设置'}
                            </Tag>
                        )}
                    </Descriptions.Item>
                    <Descriptions.Item label="创建时间">
                        {dayjs(task.createdAt).format('YYYY-MM-DD HH:mm')}
                    </Descriptions.Item>
                    <Descriptions.Item label="开始日期">
                        {task.startDate ? dayjs(task.startDate).format('YYYY-MM-DD') : '-'}
                    </Descriptions.Item>
                    <Descriptions.Item label="截止日期">
                        {task.dueDate ? dayjs(task.dueDate).format('YYYY-MM-DD') : '-'}
                    </Descriptions.Item>
                    <Descriptions.Item label="描述" span={2}>
                        {task.description || '-'}
                    </Descriptions.Item>
                </Descriptions>
            </Card>

            <Divider />

            <StepList taskId={id} />

            <Divider />

            <ReviewForm taskId={id} />
        </div>
    );
};

export default TaskDetails;
